package 第十二章_反射与内省.第十二章_反射与内省_AOP框架;

import jdk.internal.util.xml.impl.Input;
import sun.security.ec.point.ProjectivePoint;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Properties;
import java.util.stream.IntStream;

public class BeanFactory {
    Properties prop=new Properties();
    public BeanFactory(InputStream in){
        try {
            prop.load(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public Object getBean(String name) {
        String className = prop.getProperty(name);
        Object bean = null;
        try {
            Class<?> aClass = Class.forName(className);
            bean = aClass.newInstance();

            Object target = Class.forName(prop.getProperty(name + ".target")).newInstance();
            Object advice = Class.forName(prop.getProperty(name + ".advice")).newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(aClass);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for(PropertyDescriptor pd:propertyDescriptors){
                String propertyName= pd.getName();
                Method writeMethod= pd.getWriteMethod();
                if("target".equals(propertyName)) {
                    writeMethod.invoke(bean, target);
                }else if("advice".equals(propertyName)){
                    writeMethod.invoke(bean,advice);
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IntrospectionException |
                 InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        return bean;
    }
}
